package com.xinghai.service.impl;


import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.domain.*;
import com.xinghai.mapper.JkqActivityLogMapper;
import com.xinghai.mapper.JkqActivityMapper;
import com.xinghai.service.IJkqBadgeService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.mapper.JkqActivityShareMapper;
import com.xinghai.service.IJkqActivityShareService;

import javax.annotation.Resource;

/**
 * 活动分享记录Service业务层处理
 *
 * @author xinghai
 * @date 2025-08-02
 */
@Service
public class JkqActivityShareServiceImpl extends MPJBaseServiceImpl<JkqActivityShareMapper, JkqActivityShare>
        implements IJkqActivityShareService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Resource
    private JkqActivityMapper activityMapper;
    @Resource
    private JkqActivityLogMapper logMapper;
    @Autowired
    private IJkqBadgeService badgeService;
    /**
     * 查询活动分享记录列表
     *
     * @param jkqActivityShare 活动分享记录
     * @return 活动分享记录集合
     */
    @Override
    public List<JkqActivityShare> list(JkqActivityShare jkqActivityShare) {
        MPJLambdaWrapper<JkqActivityShare> query = new MPJLambdaWrapper<JkqActivityShare>()
                .setAlias("s")
                .selectAll(JkqActivityShare.class)
                .selectAs(JkqActivity::getTitle,JkqActivitySign::getTitle)
                .selectAs(JkqActivity::getImageUrl,JkqActivitySign::getImageUrl)
                .selectAs(JkqActivity::getType,JkqActivitySign::getType)
                .selectAs(JkqUser::getImageUrl,JkqActivitySign::getUserImage)
                .selectAs(JkqUser::getNickname,JkqActivitySign::getUserName)
                .selectAs(JkqUser::getHealthUserId,JkqUserBadge::getHealthUserId)
                .selectAs(JkqUserCopy::getNickname,JkqUserBadge::getHealthUserName)
                .leftJoin(JkqActivity.class, "a",JkqActivity::getId, JkqActivityShare::getActivityId)
                .leftJoin(JkqUser.class, "u",JkqUser::getId, JkqActivityShare::getUserId)
                .leftJoin(JkqUserCopy.class,"u2",JkqUserCopy::getId,JkqUser::getHealthUserId)
                .eq(jkqActivityShare.getActivityId()!= null,"s.activity_id", jkqActivityShare.getActivityId())
                .eq(jkqActivityShare.getUserId()!= null,"s.user_id", jkqActivityShare.getUserId())
                .eq(jkqActivityShare.getHealthUserId()!= null,"u.health_user_id", jkqActivityShare.getHealthUserId())
                .like(jkqActivityShare.getUserName()!= null  && !jkqActivityShare.getUserName().isEmpty(),"u.nickname", jkqActivityShare.getUserName())
                .eq(jkqActivityShare.getStatus()!= null  && !jkqActivityShare.getStatus().isEmpty(),"s.status", jkqActivityShare.getStatus())
                .orderByDesc(JkqActivityShare::getUpdateTime);
        if (jkqActivityShare.getParams().get("beginCreateTime")!= null && !"".equals(jkqActivityShare.getParams().get("beginCreateTime"))
        &&jkqActivityShare.getParams().get("endCreateTime")!= null && !"".equals(jkqActivityShare.getParams().get("endCreateTime"))){
            query.between("s.create_time", jkqActivityShare.getParams().get("beginCreateTime"),jkqActivityShare.getParams().get("endCreateTime"));
        }
        if (jkqActivityShare.getParams().get("beginUpdateTime")!= null && !"".equals(jkqActivityShare.getParams().get("beginUpdateTime"))
        &&jkqActivityShare.getParams().get("endUpdateTime")!= null && !"".equals(jkqActivityShare.getParams().get("endUpdateTime"))){
            query.between("s.update_time", jkqActivityShare.getParams().get("beginUpdateTime"),jkqActivityShare.getParams().get("endUpdateTime"));
        }
        return this.baseMapper.selectJoinList(JkqActivityShare.class,query);
    }

    /**
     * 导入活动分享记录信息
     *
     * @param list 活动分享记录信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<JkqActivityShare> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            JkqActivityShareMapper jkqActivityShareMapper = sqlSession.getMapper(JkqActivityShareMapper.class);
            list.forEach(jkqActivityShareMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }



    @Override
    public List<JkqActivityShare> getInfoByUserId(Long loginId,String status) {
        MPJLambdaWrapper<JkqActivityShare> query = new MPJLambdaWrapper<JkqActivityShare>()
                .setAlias("s")
                .selectAll(JkqActivityShare.class)
                .selectAs(JkqActivity::getTitle,JkqActivitySign::getTitle)
                .selectAs(JkqActivity::getImageUrl,JkqActivitySign::getImageUrl)
                .selectAs(JkqActivity::getType,JkqActivitySign::getType)
                .leftJoin(JkqActivity.class, "a",JkqActivity::getId, JkqActivityShare::getActivityId)
                .eq(JkqActivitySign::getActivityId, JkqActivity::getId)
                .apply("2".equals(status),"date_format(s.create_time,'%Y-%m') = date_format(now(),'%Y-%m')")
                .apply("1".equals(status),"date_format(s.create_time,'%Y-%m-%d') >= '"+DateUtils.getWeekStart()+"' and date_format(s.create_time,'%Y-%m-%d') <= '"+DateUtils.getWeekEnd()+"'")
                .eq(JkqActivitySign::getUserId, loginId)
                .orderByDesc(JkqActivityShare::getUpdateTime);
        return this.baseMapper.selectJoinList(JkqActivityShare.class,query);
    }

    @Override
    @Transactional
    public void share(JkqActivityShare activityShare) {
        this.baseMapper.insert(activityShare);
        activityMapper.updateShareNumById(activityShare.getActivityId());
        JkqActivityLog log = new JkqActivityLog();
        log.setActivityId(activityShare.getActivityId());
        log.setUserId(activityShare.getUserId());
        log.setName(activityShare.getUserName());
        log.setImageUrl(activityShare.getUserImage());
        log.setType(activityShare.getType());
        if ("0".equals(activityShare.getType())){
            log.setRemark("分享了此活动");
        }else {
            log.setRemark("传递了此活动");
        }
        logMapper.insert(log);

        //查看是否有获得的徽章
        BadgeItem badgeItem = new BadgeItem();
        badgeItem.setUserId(activityShare.getUserId());
        badgeItem.setType("3");
        badgeService.getBadgePower(badgeItem);
    }

    @Override
    public void updateShareNumByActivityId(Long activityId, Long userId) {
        baseMapper.updateShareNumByActivityId(activityId,userId);
    }
}
